package com.aisile.sellergoods.service.impl;

import com.aisile.entity.PageResult;
import com.aisile.mapper.TbSpecificationOptionMapper;
import com.aisile.mapper.TbTypeTemplateMapper;
import com.aisile.pojo.TbSpecificationOption;
import com.aisile.pojo.TbSpecificationOptionExample;
import com.aisile.pojo.TbTypeTemplate;
import com.aisile.pojo.TbTypeTemplateExample;
import com.aisile.sellergoods.service.TypeTemplateService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class TypeTemplateServiceImpl  implements TypeTemplateService{
    @Autowired
    TbTypeTemplateMapper tbTypeTemplateMapper;

    @Override
    public PageResult findPage(int page, int rows, TbTypeTemplate tbTypeTemplate) {
        PageHelper.startPage(page,rows);
        String name = tbTypeTemplate.getName();
        TbTypeTemplateExample example=new TbTypeTemplateExample();
        if(!StringUtils.isEmpty(name)){

            example.createCriteria().andNameLike("%"+name+"%");

        }
       Page<TbTypeTemplate> pageModel= (Page<TbTypeTemplate>) tbTypeTemplateMapper.selectByExample(example);

        return new PageResult(pageModel.getTotal(),pageModel.getResult());
    }

    @Override
    public void save(TbTypeTemplate tbTypeTemplate) {

        tbTypeTemplateMapper.insert(tbTypeTemplate);
    }

    @Override
    public TbTypeTemplate findOne(long id) {

        return tbTypeTemplateMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(TbTypeTemplate tbTypeTemplate) {


        tbTypeTemplateMapper.updateByPrimaryKey(tbTypeTemplate);
    }

    @Autowired
    TbSpecificationOptionMapper tbSpecificationOptionMapper;

    @Override
    public List<Map> findSpecList(long id) {

        TbTypeTemplate typeTemplate = findOne(id);
        //"[{\"id\":27,\"text\":"网络"},{"id":32,"text":"机身内存"}]" json 对象
        //List  元素类型为 Map {key:id  value:27 , key text :网络}  转化为 map
        List<Map> maps = JSON.parseArray(typeTemplate.getSpecIds(), Map.class);

        typeTemplate.getSpecIds();// String 类型 ==>js 对象

        if(maps!=null&&maps.size()>0){

            for (Map spec :maps){

                //循环遍历每一个规格

                //spec.get("id");

                //根据 id 查询出对应的规格的选项

                TbSpecificationOptionExample optionExample=new TbSpecificationOptionExample();

                optionExample.createCriteria().andSpecIdEqualTo(Long.parseLong(spec.get("id").toString()));

                List<TbSpecificationOption> optionList = tbSpecificationOptionMapper.selectByExample(optionExample);

                spec.put("options",optionList);
            }
        }
        return maps;
    }
}
